/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package swym.protocol.server;

import swym.protocol.*;
import swym.server.*;
import swym.server.file.*;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 *
 * @author mschaefer
 */
public class UpdateMessageHandler extends MessageHandler
{
    public UpdateMessageHandler( ActionMessage message ) 
            throws MessageException
    {
        super( message );
    }
    
    /**
     * 
     * @param socket
     * @throws java.io.IOException
     */
    public void handleMessage( ClientSocket socket ) throws IOException
    {     
        // gather all of the pending file actions 
        // and add them to the response queue
        Vector<FileAction> actions = getUser().getFileActionManager().getFileActions();
        Vector<FileActionMessage> actionMessages = new Vector<FileActionMessage>();

        for ( int i = actions.size() - 1; i >= 0; i-- )
        {
            if ( actions.get( i ).isClientUpdated( getClient() ) )
                actions.remove( i );
            else
            {
                FileActionMessage message = new FileActionMessage( getUser().getName(), 
                                                                   getClient().getName(), 
                                                                   actions.get(i).getType(), getRequestID() );

                // replace the action with a shallow copy (excludes file data chunks)
                actionMessages.add( message );
            }
        }

        if ( actionMessages.size() > 0 )
        {
            ConfirmActionMessage message = new ConfirmActionMessage( getUser().getName(), 
                                                                     getClient().getName(), 
                                                                     getRequestID() );
            message.setPayload( actionMessages );
            
            writeMessage( socket, message );
        }
    }
}
